package cn.zebra.dev.admin.module.security.manager;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @author runnable@sina.cn
 */
@Slf4j
@Component
public class AdminDecisionManager implements AccessDecisionManager {
    @SneakyThrows
    @Override
    public void decide(Authentication authentication, Object invocation, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        // 遍历角色
        for (ConfigAttribute configAttribute : collection) {
            //  当前url请求需要的权限
            String attribute = configAttribute.getAttribute();
            //该账号角色
            if (authentication.getAuthorities().stream().anyMatch(authority -> authority.getAuthority().equals(attribute))) {
                return;
            }
        }
        throw new AccessDeniedException("无权限访问！");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
